package com.longteng.diamond.util;

import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by Administrator
 * DATE : 2018/7/5
 * TIME : 21:04
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Component
public class ValidUtil {
    /**
     * @description jsr303基础校验,遍历 field是为了每次有顺序的提醒
     * @param
     * @return
     */
    public boolean checkParam(Field[] declaredFields, BindingResult bindingResult, ModelAndView modelAndView) {
        boolean isPass = true;
        if (bindingResult.hasErrors()) {
            isPass = false;
            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            for (Field field : declaredFields) {
                String fieldName = field.getName();
                boolean find = false;
                for (FieldError fieldError : fieldErrorList) {
                    String fieldErrorName = fieldError.getField();
                    if (fieldName.equalsIgnoreCase(fieldErrorName)) {
                        find = true;
                        modelAndView.addObject("errorMsg", fieldError.getDefaultMessage());
                        break;
                    }
                }
                if (find) {
                    break;
                }
            }
        }
        return isPass;
    }
}
